﻿using ConfExpert.Datasets;
using ConfExpert.Forms.Base;
using ConfExpert.Utility;
using DevExpress.XtraPivotGrid;
using DevTeam;
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Depo._7C
{
    public partial class KumasVeUretim : XForm
    {
        int CKBatchId = -1;
        public KumasVeUretim(int ckBatchId)
        {
            InitializeComponent();

            this.CKBatchId = ckBatchId;
            this.Text += "- " + AppSession.Lookups.CKBatch.FindByCKBatchId(CKBatchId).Notes;
        }

        private void KumasVeUretim_Load(object sender, EventArgs e)
        {
            //this.panelControl1.Visible = false;
            //bs = new BindingSource(ds, "xOrdine");
            RefreshData();
            ExpandCollapse(splitContainerControl1, AcKapa.Collapse);

            pvg.OptionsPrint.PrintColumnHeaders = DevExpress.Utils.DefaultBoolean.False;
            pvg.OptionsPrint.PrintDataHeaders = DevExpress.Utils.DefaultBoolean.False;
            pvg.OptionsPrint.PrintFilterHeaders = DevExpress.Utils.DefaultBoolean.False;
            pvg.OptionsPrint.MergeRowFieldValues = false;
            pvg.OptionsPrint.MergeColumnFieldValues = false;

            splitContainerControl1.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Panel1;

        }

        BindingSource bs;
        void pivotGridControl1_CustomAppearance(object sender, PivotCustomAppearanceEventArgs e)
        {
            if (e.Focused)
                e.Appearance.BackColor = e.Appearance.BackColor2 = Color.YellowGreen;   // Color.FromArgb(255, 192, 0);
        }


        void RefreshData()
        {
            bs = gridView1.Init("Get7cKumasVeUretim", CKBatchId);

            if (AppSession.SonArama.ToStr() != string.Empty)
                bs.Filter = "ISNULL(ProductId,0) in (" + AppSession.SonArama + ",-1)";

            //DrillDownGrid(gridView1, bs);
            //gridView1.AddSummary("Qty");
            //gridView1.OptionsBehavior.Editable = false;

            InitPivot(pvg, bs);

            //GetDetails("xOrdine", "Get7cOrdine", CKBatchId);
            //gridView1.Columns["idx"].Visible = 
            //gridView1.Columns["CodCliente"].Visible = false;
            pvg.Cells.Selection = new Rectangle(new Point(0, 0), new Size(1, 1));
            //pvg.Fields["ProductId"].BestFit();
            pvg.BestFit();

        }

        void pgc_CustomDrawFieldValue(object sender, PivotCustomDrawFieldValueEventArgs e)
        {
            if (e.Field == pvg.Fields["CikisPartisiId"])
            {
                string caption = ((DevExpress.Utils.Drawing.HeaderObjectInfoArgs)e.Info).Caption;
                ((DevExpress.Utils.Drawing.HeaderObjectInfoArgs)e.Info).Caption = string.Empty;
                e.Painter.DrawObject(e.Info);
                Rectangle rec = new Rectangle(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height - 5);
                e.GraphicsCache.DrawVString(caption, e.Appearance.GetFont(), e.Appearance.GetForeBrush(e.GraphicsCache), rec, e.Appearance.GetStringFormat(), 270);
                e.Handled = true;
            }
        }

        ImageList imageList1;
        bool PivotInitialized = false;
        void InitPivot(PivotGridControl pgc, BindingSource bs)
        {
            pgc.DataSource = bs;

            if (!PivotInitialized)
            {
                imageList1 = new ImageList();
                imageList1.ImageSize = new Size(32, 32);
                imageList1.ColorDepth = ColorDepth.Depth16Bit;

                foreach (DataRow dr in gridView1.Dataset().Tables[1].Rows)
                {
                    MyData.V_KumasRow productRow = AppSession.Lookups.V_Kumas.FindByProductId(dr["ProductId"].ToInt());

                    if (!productRow.IsPhotoMikroNull())
                        imageList1.Images.Add(productRow.Name, ConvertByteArrayToImage(productRow.PhotoMikro));
                }

                pgc.ValueImages = imageList1;
                pgc.FieldValueImageIndex += pgc_FieldValueImageIndex;
                pgc.OptionsCustomization.CustomizationFormStyle = DevExpress.XtraPivotGrid.Customization.CustomizationFormStyle.Excel2007;
                //pgc.CellClick += new PivotCellEventHandler(pivotGridControl1_CellClick);
                pgc.CellSelectionChanged += new EventHandler(pgc_CellSelectionChanged);
                pgc.FocusedCellChanged += new EventHandler(pgc_FocusedCellChanged);
                pgc.FieldValueDisplayText += new PivotFieldDisplayTextEventHandler(pivotGrid_FieldValueDisplayText);
                pgc.CustomAppearance += new PivotCustomAppearanceEventHandler(pivotGridControl1_CustomAppearance);
                pgc.CustomDrawFieldValue += pgc_CustomDrawFieldValue;

                pgc.BeginUpdate();

                //new field - toplam tutar  (metre x fiyat+dvz cinsi)

                //AddNewField(pgc, "DosyaNo", PivotArea.FilterArea);
                //AddNewField(pgc, "CodCliente", PivotArea.FilterArea);
                //AddNewField(pgc, "Linea", PivotArea.FilterArea);
                /*
                PivotGridFieldBase[] pgf1 = new PivotGridFieldBase[3];
                pgf1[0] = AddNewField(pgc, "Linea", PivotArea.RowArea);
                pgf1[1] = AddNewField(pgc, "Modello", PivotArea.RowArea);
                pgf1[1].ExpandedInFieldsGroup = false;
                pgf1[2] = AddNewField(pgc, "Tex", PivotArea.RowArea);
                pgc.Groups.Add(pgf1, "ModelloTex");
                */

                PivotGridField qa = AddNewField(pgc, "QtyAvailable", PivotArea.RowArea);
                qa.ValueFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                qa.ValueFormat.FormatString = "#,###.0";
                qa.Appearance.Value.Options.UseTextOptions = true;
                qa.Appearance.Value.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;

                //AddNewField(pgc, "ProductId", PivotArea.RowArea).Visible = false;   //.FieldEdit = RI(Rp.V_Kumas);
                AddNewField(pgc, "Art", PivotArea.RowArea);
                AddNewField(pgc, "CikisPartisiId", PivotArea.ColumnArea);

                AddNewField(pgc, "Qty", PivotArea.DataArea).Caption = "CikilanMiktar";


                //.Width = 40;  .Visible = true;
                //    fld.SummaryType = DevExpress.Data.PivotGrid.PivotSummaryType.Sum;

                //foreach (PivotGridField pgf in pgc.Fields)
                //{
                //    pgf.SortOrder = PivotSortOrder.Ascending;
                //    pgf.Options.AllowSort = DevExpress.Utils.DefaultBoolean.True;
                //}
                pgc.EndUpdate();

                PivotInitialized = true;
            }
        }

        void pgc_FieldValueImageIndex(object sender, PivotFieldImageIndexEventArgs e)
        {
            if (e.Field != null)
                if (e.Field.FieldName == "Art")
                    if (imageList1.Images.ContainsKey(e.Value.ToString()))
                        e.ImageIndex = imageList1.Images.IndexOfKey(e.Value.ToString());
        }

        void pgc_FocusedCellChanged(object sender, EventArgs e)
        {
            CellChanged();
        }


        void pgc_CellSelectionChanged(object sender, EventArgs e)
        {
            CellChanged();
        }

        private void CellChanged()
        {
            double PivotSum = 0.0;

            if (pvg.Cells.MultiSelection.SelectedCells.Count > 0)
            {
                foreach (Point cell in pvg.Cells.MultiSelection.SelectedCells)
                {
                    DevExpress.XtraPivotGrid.PivotCellEventArgs cellInfo = pvg.Cells.GetCellInfo(cell.X, cell.Y);
                    if (cellInfo.ColumnValueType == DevExpress.XtraPivotGrid.PivotGridValueType.Value &&
                        cellInfo.RowValueType == DevExpress.XtraPivotGrid.PivotGridValueType.Value)
                        PivotSum += Convert.ToDouble(pvg.GetCellValue(cell.X, cell.Y));
                }
            }
            else
            {
                DevExpress.XtraPivotGrid.PivotCellEventArgs cellInfo = pvg.Cells.GetFocusedCellInfo();
                if (cellInfo.ColumnValueType == DevExpress.XtraPivotGrid.PivotGridValueType.Value &&
                    cellInfo.RowValueType == DevExpress.XtraPivotGrid.PivotGridValueType.Value)
                    PivotSum += Convert.ToDouble(pvg.GetCellValue(pvg.Cells.FocusedCell.X, pvg.Cells.FocusedCell.Y));

            }
            Notify(PivotSum == 0 ? string.Empty : String.Format("{0:#,##0.## mt'.'}", PivotSum));
        }

        void pivotGridControl1_CellClick(object sender, DevExpress.XtraPivotGrid.PivotCellEventArgs e)
        {
            gridControl1.DataSource = e.CreateDrillDownDataSource();
            gridView1.MakeColumnInvisible("Name");
            ExpandCollapse(splitContainerControl1, (gridView1.RowCount > 0 ? AcKapa.Expand : AcKapa.Collapse));
            gridView1.BestFitColumns();
            gridView1.MoveFirst();
        }
    }
}
